//
//  Plugnetwork.m
//  Mokey
//
//  Created by YQ05 on 2018/7/26.
//  Copyright © 2018年 OR Media. All rights reserved.
//

#import "network.h"
#import "DataPersist.h"
#import "../../DataSource.h"
#import "MKConstant.h"

#import "setLocalnoti.h"

@implementation network
    
    -(void) AppGetHomeBanner{  //传入MAC_ID //创建请求路径
        
        //macid=macid;  //内部复制
        
        //NSURL *url=[NSURL URLWithString:@"http://mokey.site/app-message/?device_id=8895f3&message=relays_one|1"];
        
        //NSString *domain = @"http://youngplus.com.hk/app-get-home-banner";
        
        //NSString *domain = @"http://youngplus.com.hk/app-get-services";// ?platform=ios
        NSString *domain = @"http://youngplus.com.hk/app-get-services?after=20181230";  //固定时间
        //NSString *str2 = [domain stringByAppendingString:macid];
        //NSString *str3 = @"&message=relays_one|1";
        
        NSString *requestRUL = domain;
        
        //    NSString *urlutf8 = [@"http://mokey.site/app-message/?device_id=8895f3&message=relays_one|1" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%^{}\"[]|\\<> "].invertedSet];
        
        NSString *urlutf8 = [requestRUL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%^{}\"[]|\\<> "].invertedSet];
        NSURL *url=[NSURL URLWithString:urlutf8];
        NSLog(@"url : %@",url);
        
        //创建请求对象
        NSURLRequest *request=[NSURLRequest requestWithURL:url];
        //创建会话对象
        NSURLSession *session=[NSURLSession sharedSession];
        //根据会话对象来创建请求任务 任务中的代码块默认在子线程中执行
        //__weak __typeof(self) weakSelf = self;
        NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
                                        {
                                            NSLog(@"向服务器发送请求");
                                            //json 解析
                                            //NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
                                            // 请求失败，打印错误信息
                                            if (error) {
                                                NSLog(@"%@", error.localizedDescription);
                                                     //网络请求 延迟时间 重新申请数据
                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, 5000*NSEC_PER_MSEC);
                                                    // 延迟方法
                                                    // 1 delayTime 2 thread 3 代码
               dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                     NSLog(@"重新向服务器申请数据");
                     [self AppGetHomeBanner];
                   
                                    });
                                        //
                                            }
                                            // 8、请求成功，解析数据
                                            else {
                                                NSLog(@"成功获取网络信息");
                                                // 直接将data数据转成OC字符串(NSUTF8StringEncoding)；
                                                //NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                                
                                                // JSON数据格式解析
                                                id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
                                                
                                               
                                                //return array;
                                                
                                                // 9、判断是否解析成功
                                                if (error) {
                                                    NSLog(@"%@", error.localizedDescription);
                                                }else {
                                                    //NSLog(@"%@", object);
                                                    // 解析成功，处理数据，通过GCD获取主队列，在主线程中刷新界面。
                                                    dispatch_async(dispatch_get_main_queue(), ^{
                                                        NSLog(@"在主线程中刷新界面");
                                                        // 刷新界面....
                                                        NSMutableArray *array =  object; //[jsonDic valueForKey:@"people"];
                                                        
                                                        //NSLog(@"%@",[object class]);
                                                        //NSLog(@"%@",array);
                                                        
                                                        
                                                        
          [DataPersist writeValueNSMutableArray:array key:@"homeindex"];//数据持久化
 [[NSNotificationCenter defaultCenter]postNotificationName:@"getIndexNOTIF" object:nil];  //数据加载成功
                                                    });
                                                }
                                            }
                                        }];
        //执行任务（发送请求）
        [dataTask resume];
        
    }



-(void) itemVcgetJsonData:(NSString*)cate item:(NSString*)item{  //子页面WKwebkit请求数据
    
    //macid=macid;  //内部复制
    
    NSString *domain = @"";
    if ([cate isEqualToString:@"id"]) {  //判断请求类型
        //domain = @"http://youngplus.com.hk/app-get-service-detail?platform=ios&id=";  // ?platform=ios
         domain = @"http://youngplus.com.hk/app-get-service-detail?id=";  // ?platform=ios
    }else if ([cate isEqualToString:@"promotionid"]) {
        domain = @"http://youngplus.com.hk/app-get-promotions?id=";  // ?platform=ios
    }else if ([cate isEqualToString:@"getreport"]) {
        domain = [NSString stringWithFormat:@"%@%@?debug=1&uid=",YOUNGURL,GETREPORTPAGE];
    }else{
        domain = @"http://youngplus.com.hk/app-get-service-detail?title="; // ?platform=ios
    }
    
    NSLog(@"promotionid itemVcgetJsonData %@",item);
    
    //NSURL *url=[NSURL URLWithString:@"http://youngplus.com.hk/app-get-service-detail?id=79"];
    
    
    NSString *str2 = [domain stringByAppendingString:item];
    
    NSString *requestRUL = str2;
    
    //    NSString *urlutf8 = [@"http://mokey.site/app-message/?device_id=8895f3&message=relays_one|1" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%^{}\"[]|\\<> "].invertedSet];
    
    NSString *urlutf8 = [requestRUL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%^{}\"[]|\\<> "].invertedSet];
    NSURL *url=[NSURL URLWithString:urlutf8];
    NSLog(@"url : %@",url);
    
    //创建请求对象
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    //创建会话对象
    NSURLSession *session=[NSURLSession sharedSession];
    //根据会话对象来创建请求任务 任务中的代码块默认在子线程中执行
   // __weak __typeof(self) weakSelf = self;
    NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
                                    {
                                        NSLog(@"向服务器发送请求");
                                        //json 解析
                                        //NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
                                        // 请求失败，打印错误信息
                                        if (error) {
                                            NSLog(@"%@", error.localizedDescription);
                                            //网络请求 延迟时间 重新申请数据
                                            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, 5000*NSEC_PER_MSEC);
                                            // 延迟方法
                                            // 1 delayTime 2 thread 3 代码
                                            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                                                NSLog(@"重新向服务器申请数据");
                                                [self itemVcgetJsonData:cate item:item];
                                            });
                                            //
                                        }
                                        // 8、请求成功，解析数据
                                        else {
                                            NSLog(@"成功获取网络信息");
                                            // 直接将data数据转成OC字符串(NSUTF8StringEncoding)；
                                            //NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                            
                                            // JSON数据格式解析
                                            id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
                                            
                                            
                                            //return array;
                                            
                                            // 9、判断是否解析成功
                                            if (error) {
                                                NSLog(@"%@", error.localizedDescription);
                                            }else {
                                                //NSLog(@"%@", object);
                                                // 解析成功，处理数据，通过GCD获取主队列，在主线程中刷新界面。
                                                dispatch_async(dispatch_get_main_queue(), ^{
                                                    NSLog(@"在主线程中刷新界面");
                                                    // 刷新界面....
                                                    NSMutableArray *array =  object; //[jsonDic valueForKey:@"people"];
                                                    
                                                    //NSLog(@"%@",[object class]);
                                             //   NSLog(@"%@",array);
                                                    
                                                    
                                                    
     [DataPersist writeValueNSMutableArray:array key:@"itemData"];//数据持久化
    [[NSNotificationCenter defaultCenter]postNotificationName:@"getitemDataNOTIF" object:nil];  //数据加载成功
                                                });
                                            }
                                        }
                                    }];
    //执行任务（发送请求）
    [dataTask resume];
    
}

-(void)GETInfo:(NSString*)urlString type:(NSString *)type senddic:(NSMutableDictionary *)senddic savekey:(NSString*)savekey
{
    //对请求路径的说明
    //http://127.25.26.001:32812/login?username=520it&pwd=520&type=JSON
    //协议头+主机地址+接口名称+？+参数1&参数2&参数3
    //协议头(http://)+主机地址(120.25.226.186:32812)+接口名称(login)+？+参数1(username=520it)&参数2(pwd=520)&参数3(type=JSON)
    //GET请求，直接把请求参数跟在URL的后面以？隔开，多个参数之间以&符号拼接
    
    NSString *page = @"";
    if ([type isEqualToString:@"getSchedule"]){
        //NSString *params = [NSString stringWithFormat:@"?debug=1&action=get&uid=%@", [senddic valueForKey:@"uid"]];
        //page = [GETSCHEDULEPAGE stringByAppendingFormat:@"%@",params];
        
        page = @"lau-test?action=10";
    }
    
    NSString *requestRUL = [urlString stringByAppendingString:page];
    
    NSString *urlutf8 = [requestRUL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%^{}\"[]|\\<> "].invertedSet];
//    NSURL *url=[NSURL URLWithString:urlutf8];
    NSLog(@"url : %@",urlutf8);

    //1.确定请求路径
     //NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"];
     NSURL *url = [NSURL URLWithString:urlutf8];

     //2.创建请求对象
     //请求对象内部默认已经包含了请求头和请求方法（GET）
     NSURLRequest *request = [NSURLRequest requestWithURL:url];

     //3.获得会话对象
     NSURLSession *session = [NSURLSession sharedSession];

     //4.根据会话对象创建一个Task(发送请求）
     /*
      第一个参数：请求对象
      第二个参数：completionHandler回调（请求完成【成功|失败】的回调）
              data：响应体信息（期望的数据）
              response：响应头信息，主要是对服务器端的描述
              error：错误信息，如果请求失败，则error有值
      */
     NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  
          if (error == nil) {
                   //6.解析服务器返回的数据
                   //说明：（此处返回的数据是JSON格式的，因此使用NSJSONSerialization进行反序列化处理）
                   NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
      
                   NSLog(@"%@",dict);
              
              NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
              if (data && httpResponse.statusCode == 200) {
                  //8.解析数据
                  NSDictionary *datadic = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
                  // NSLog(@"%@",datadic.allValues);
                  
                  // NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
                  // NSLog(@"%@",datadic);
                  
                  //字符串先复制 再使用
        //NSString *rc = [datadic valueForKey:@"rc"]; //[rc isEqualToString:@"1"]
                  //NSString *rcstr = [NSString stringWithFormat:@"%@",@"1"];
                  //NSString *rcstr = [NSString stringWithFormat:@"%@",rc];
                  // NSLog(@"rcstr %@",rcstr);
                  
                  #pragma remark getSchedule
                  if ([type isEqualToString:@"getSchedule"]){
//                      NSString  *scstr = [NSString stringWithFormat:@"%@",@"0"];
//                      NSMutableDictionary *backdic = [[NSMutableDictionary alloc]init]; //返回數據字典
                      BOOL testflag = true;
                      if (testflag) { //[rcstr isEqual:scstr]
                          NSLog(@"network 本地推送获取数据成功");
                          NSLog(@"成功获取网络信息");
                          // 直接将data数据转成OC字符串(NSUTF8StringEncoding)；
                          //NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                          // JSON数据格式解析
                          id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
                          // 刷新界面....
                          NSMutableDictionary *backdic = object;
                          //NSLog(@"%@",[object class]);
                          //NSLog(@"%@",backdic);
                          NSMutableArray *array = [backdic valueForKey:@"data"];
                          NSLog(@"%@",array);
                          
                          [DataPersist writeValueNSMutableArray:array key:@"getSchedule"];//数据持久化
                          //                                                    [[NSNotificationCenter defaultCenter]postNotificationName:@"getScheduleStatus" object:[NSNumber numberWithInt:1] userInfo:backdic];
                          setLocalnoti *younglocalnoti = [[setLocalnoti alloc]init];
                          [younglocalnoti getScheduleAction];
                          
                      }
               }
                  //结束
              }else{
                  NSLog(@"network get 网络请求失败");
                  // 直接将data数据转成OC字符串(NSUTF8StringEncoding)；
                  //NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                  
                  // JSON数据格式解析
                  id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
                  // 刷新界面....
                  //NSMutableArray *array =  object; //[jsonDic valueForKey:@"people"];
                  NSMutableDictionary *backdic = object;
                  //NSLog(@"%@",[object class]);
                  //NSLog(@"%@",backdic);
                  NSMutableArray *array = [backdic valueForKey:@"data"];
                  NSLog(@"%@",array);
              }
          }
       }];

     //5.执行任务
     [dataTask resume];
 }



-(void) promotionVcgetJsonData:(NSString*)cate item:(NSString*)item{  //子页面WKwebkit请求数据
    NSLog(@"itemVcgetJsonData");
    //macid=macid;  //内部复制
    
    NSString *domain = @"";
    if ([cate isEqualToString:@"id"]) {  //判断请求类型
        domain = @"http://youngplus.com.hk/app-get-service-detail?id=";  // ?platform=ios
    }else{
        domain = @"http://youngplus.com.hk/app-get-service-detail?title="; // ?platform=ios platform=ios&
    }
    
    //NSURL *url=[NSURL URLWithString:@"http://youngplus.com.hk/app-get-service-detail?id=79"];
    
    
    NSString *str2 = [domain stringByAppendingString:item];
    //NSString *str3 = @"&message=relays_one|1";
    
    NSString *requestRUL = str2;
    
    //    NSString *urlutf8 = [@"http://mokey.site/app-message/?device_id=8895f3&message=relays_one|1" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%^{}\"[]|\\<> "].invertedSet];
    
    NSString *urlutf8 = [requestRUL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%^{}\"[]|\\<> "].invertedSet];
    NSURL *url=[NSURL URLWithString:urlutf8];
    NSLog(@"url : %@",url);
    
    //创建请求对象
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    //创建会话对象
    NSURLSession *session=[NSURLSession sharedSession];
    //根据会话对象来创建请求任务 任务中的代码块默认在子线程中执行
    NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
                                    {
                                        
                                        NSLog(@"向服务器发送请求");
                                        //json 解析
                                        //NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
                                        // 请求失败，打印错误信息
                                        if (error) {
                                            NSLog(@"%@", error.localizedDescription);
                                            //网络请求 延迟时间 重新申请数据
                                            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, 5000*NSEC_PER_MSEC);
                                            // 延迟方法
                                            // 1 delayTime 2 thread 3 代码
                                            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                                                NSLog(@"重新向服务器申请数据");
                                                [self itemVcgetJsonData:cate item:item];
                                            });
                                            //
                                        }
                                        // 8、请求成功，解析数据
                                        else {
                                            NSLog(@"成功获取网络信息");
                                            // 直接将data数据转成OC字符串(NSUTF8StringEncoding)；
                                            //NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                            
                                            // JSON数据格式解析
                                            id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
                                            
                                            
                                            //return array;
                                            
                                            // 9、判断是否解析成功
                                            if (error) {
                                                NSLog(@"%@", error.localizedDescription);
                                            }else {
                                                //NSLog(@"%@", object);
                                                // 解析成功，处理数据，通过GCD获取主队列，在主线程中刷新界面。
                                                dispatch_async(dispatch_get_main_queue(), ^{
                                                    NSLog(@"在主线程中刷新界面");
                                                    // 刷新界面....
                                                    NSMutableArray *array =  object; //[jsonDic valueForKey:@"people"];
                                                    
                                                    //NSLog(@"%@",[object class]);
                                                    NSLog(@"%@",array);
                                                    
                                                    
                                                    
                                                    [DataPersist writeValueNSMutableArray:array key:@"itemData"];//数据持久化
                                                    [[NSNotificationCenter defaultCenter]postNotificationName:@"getitemDataNOTIF" object:nil];  //数据加载成功
                                                });
                                            }
                                        }
                                    }];
    //执行任务（发送请求）
    [dataTask resume];
    
}

-(void) plugGetOn:(NSString*) macid{  //传入MAC_ID //创建请求路径
    
    macid=macid;  //内部复制
    
    //NSURL *url=[NSURL URLWithString:@"http://mokey.site/app-message/?device_id=8895f3&message=relays_one|1"];
    
    NSString *domain = @"http://mokey.site/app-message/?device_id=";
    NSString *str2 = [domain stringByAppendingString:macid];
    NSString *str3 = @"&message=relays_one|1";
    
    NSString *requestRUL = [str2 stringByAppendingString:str3];
    
    //    NSString *urlutf8 = [@"http://mokey.site/app-message/?device_id=8895f3&message=relays_one|1" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%^{}\"[]|\\<> "].invertedSet];
    
    NSString *urlutf8 = [requestRUL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%^{}\"[]|\\<> "].invertedSet];
    NSURL *url=[NSURL URLWithString:urlutf8];
    
    
    //创建请求对象
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    //创建会话对象
    NSURLSession *session=[NSURLSession sharedSession];
    //根据会话对象来创建请求任务 任务中的代码块默认在子线程中执行
    NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
                                    {
                                        NSLog(@"向服务器发送ON请求");
                                        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
                                        // 请求失败，打印错误信息
                                        if (error) {
                                            NSLog(@"%@", error.localizedDescription);
                                        }
                                        // 8、请求成功，解析数据
                                        else {
                                            
                                            // 直接将data数据转成OC字符串(NSUTF8StringEncoding)；
                                            // NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                            
                                            // JSON数据格式解析
                                //            id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
                                            // 9、判断是否解析成功
                                            if (error) {
                                                NSLog(@"%@", error.localizedDescription);
                                            }else {
                                                //NSLog(@"%@", object);
                                                // 解析成功，处理数据，通过GCD获取主队列，在主线程中刷新界面。
                                                dispatch_async(dispatch_get_main_queue(), ^{
                                                    // 刷新界面....
                                                });
                                            }
                                        }
                                    }];
    //执行任务（发送请求）
    [dataTask resume];
    
}



-(void) plugGetOff:(NSString*) macid  //传入MAC_ID //创建请求路径
{
    
    //    NSString *urlutf8 = [@"http://mokey.site/app-message/?device_id=8895f3&message=relays_one|0" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%^{}\"[]|\\<> "].invertedSet];
    
    macid=macid;  //内部复制
    
    NSString *domain = @"http://mokey.site/app-message/?device_id=";
    NSString *str2 = [domain stringByAppendingString:macid];
    NSString *str3 = @"&message=relays_one|0";
    
    NSString *requestRUL = [str2 stringByAppendingString:str3];
    
    NSString *urlutf8 = [requestRUL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%^{}\"[]|\\<> "].invertedSet];
    NSURL *url=[NSURL URLWithString:urlutf8];
    
    // 1.创建一个网络路径
    //NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://mokey.site/"]];
    // 2.创建一个网络请求
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    // 3.获得会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    // 4.根据会话对象，创建一个Task任务：
    NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"向服务器发送OFF请求");
        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
        /*
         对从服务器获取到的数据data进行相应的处理：
         */
        //NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
    }];
    // 5.最后一步，执行任务（resume也是继续执行）:
    [sessionDataTask resume];
}

- (NSMutableArray *)plugInfoJson{
    // Do any additional setup after loading the view, typically from a nib.
    NSString *jsonPath = [[NSBundle mainBundle]pathForResource:@"text" ofType:@"json"];
    NSData *jsonData = [NSData dataWithContentsOfFile:jsonPath];
    NSError *error;
    // 1 content->nsdata 2 data->full parse 3 error
    id jsonContent = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    // 1
    //NSDictionary *jsonDic = jsonContent;
    // 2
    NSMutableArray *array =  jsonContent; //[jsonDic valueForKey:@"people"];
    // 3
    //    for (NSDictionary *item in array) {
    //        for (NSString *key in item.allKeys) {
    //            NSDictionary *value1 = [item valueForKey:key];
    //            NSLog(@"%@",key);
    //            // 4
    //            for (NSString *interKey in value1.allKeys) {
    //                NSString *interValue = [value1 valueForKey:interKey];
    //                NSLog(@"%@ %@",interKey,interValue);
    //            }
    //        }
    //    }
    
    /*  显示所有 key - value
     for (NSDictionary *item in array) {
     
     // 4
     for (NSString *item2 in item ) {
     NSLog(@"item=%@",item2);
     NSLog(@"item2 value=%@",[item valueForKey:item2]);
     }
     
     }
     */
    //    for (NSString *item in array) {
    //        NSLog(@"item=%@",item);
    //    }
    
    
    //NSLog(@"%@",jsonDic);
    //NSLog(@"%@",array);
    //
    NSLog(@"%@",[jsonContent class]);
    return array;
}
    
    
   -(void) getnetworkimg:(NSString*) url
    {
        //原文：https://blog.csdn.net/luoshengkim/article/details/51037912
//        Cache缓存+同步加载
//        第一次加载的时候用同步加载，同时把图片缓存到沙箱目录中，第二次及以后的加载就直接从本地目录中加载。
//        1）首先建立一个缓存目录
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString * diskCachePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"imageCache"];
        
        //如果目录imageCache不存在，创建目录
        if (![[NSFileManager defaultManager] fileExistsAtPath:diskCachePath]) {
            NSLog(@"img1");
            NSError *error = nil;
            [[NSFileManager defaultManager] createDirectoryAtPath:diskCachePath withIntermediateDirectories:YES attributes:nil error:&error];
        }
        
        //2）如果本地缓存没有，则保存图片到对应的路径。若本地缓存有图片，则直接从缓存中加载图片
//        for (int i = 0; i < self.urlArray.count; i++) {
//            NSURL *imageURL = self.urlArray[i];
//            
//            // 如果本地缓存没有，保存图片
//            NSString *localPath = [NSString stringWithFormat:@"%@/headimage%d.png", diskCachePath, i];
//            if (![[NSFileManager defaultManager] fileExistsAtPath:localPath]) {
//                NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
//                [imageData writeToFile:localPath atomically:YES];
//            }
//            
//            // 如果存在本地缓存图片，直接读取cache内的缓存图片
//            if ([[NSFileManager defaultManager] fileExistsAtPath:localPath]) {
//                NSData *data = [NSData dataWithContentsOfFile:localPath];
//                UIImage *image = [UIImage imageWithData:data];
//                [self.imageArray addObject:image];
//            }
//        }
       
        
        
        
    }

#pragma remaek POST网络请求
//POST网络请求
-(void)POSTrequest:(NSString*)urlString type:(NSString *)type senddic:(NSMutableDictionary *)senddic savekey:(NSString*)savekey{
    BOOL debug = true;
    
    
    NSString *page = @"";
    if ([type isEqualToString:@"Promotion"]) {
        page = @"app-promotion/";
    }else if ([type isEqualToString:@"login"]){
        page = @"app-login/";
    }else if ([type isEqualToString:@"contactUs"]){
        page = BOOKINGPAGE;
    }else if ([type isEqualToString:@"register"]){
        page = REGISTERPAGE;
    }else if ([type isEqualToString:@"resetpass"]){
        page = RESETPASSRPAGE;
    }else if ([type isEqualToString:@"getSchedule"]){
        page = GETSCHEDULEPAGE;
    }
    

    
    //NSMutableDictionary *sdic = [senddic mutableCopy];
    
    //http://youngplus.com.hk/app-promotion/?username=xxx&userphone=xxx&useremail=xxx&title=xxx&to=自己邮箱
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",urlString,page];
    NSLog(@"urlStr : %@",urlStr);
    //对请求路径的说明
    //http://120.25.226.001:32812/login
    //协议头+主机地址+接口名称
    //协议头(http://)+主机地址(120.25.226.001:32812)+接口名称(login)
    //POST请求需要修改请求方法为POST，并把参数转换为二进制数据设置为请求体
    
    //1.创建会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    
    //2.根据会话对象创建task
    NSURL *url = [NSURL URLWithString:urlStr];
    
    //3.创建可变的请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    //4.修改请求方法为POST
    request.HTTPMethod = @"POST";
    
    //5.设置请求体
    //NSString *bodystr = [NSString stringWithFormat:@"login_name=%@&psw=%@&action=login",userName,password];
    NSString *bodystr = @"";
    if ([type isEqualToString:@"Promotion"]) {
        NSMutableDictionary *sdic = [senddic mutableCopy];;
        NSLog(@"s接受到的 字典。%@",sdic);
        NSString *username = [sdic valueForKey:@"username"];
        NSString *userphone = [sdic valueForKey:@"userphone"];
        NSString *useremail = [sdic valueForKey:@"useremail"];
        NSString *usersex = [sdic valueForKey:@"usersex"];
        NSString *title = [sdic valueForKey:@"title"];
        if (debug) {
            NSString *debugemail = @"zellop@21cn.com";
            
bodystr = [NSString stringWithFormat:@"username=%@&userphone=%@&useremail=%@&title=%@&usersex=%@&to=%@",username,userphone,useremail,title,usersex,debugemail];
            
 
        }else{
            
            bodystr = [NSString stringWithFormat:@"username=%@&userphone=%@&useremail=%@&title=%@&usersex=%@",username,userphone,useremail,title,usersex];
            

        }
        
    }else if ([type isEqualToString:@"login"]){  //登录请求
        [[DataSource getInstance]setLoginFlag:false]; //登錄狀態
        [DataPersist writeValuePre:@"0" key:@"loginStatus"];
        NSMutableDictionary *sdic = [senddic mutableCopy];;
        NSLog(@"s接受到的 字典。%@",sdic);
        NSString *username = [sdic valueForKey:@"username"];
        NSString *userpass = [sdic valueForKey:@"userpass"];
        NSString *token = [sdic valueForKey:@"fcmToken"];


       bodystr = [NSString stringWithFormat:@"username=%@&userpass=%@&token=%@",username,userpass,token];
   
     
    }else if ([type isEqualToString:@"contactUs"]){  //联系我们 预约
#pragma remark 联系我们 预约
        NSMutableDictionary *sdic = [senddic mutableCopy];;
//        NSLog(@"s接受到的 字典。%@",sdic);
        NSString *username = [sdic valueForKey:@"username"];
        NSString *phone = [sdic valueForKey:@"phone"];
        NSString *sex = [sdic valueForKey:@"sex"];
         NSString *service = [sdic valueForKey:@"service"];
         NSString *msg = [sdic valueForKey:@"msg"];
        NSString *action = [sdic valueForKey:@"action"];
        
        //bodystr = [NSString stringWithFormat:@"username=%@&userpass=%@&token=%@",username,phone,token];
        
        
        bodystr = [NSString stringWithFormat:@"username=%@",username];

        NSString *tags1 = [NSString stringWithFormat:@"&phone=%@",phone];
        NSString *tags2 = [NSString stringWithFormat:@"&sex=%@",sex];
        NSString *tags3 = [NSString stringWithFormat:@"&service=%@",service];
        NSString *tags4 = [NSString stringWithFormat:@"&msg=%@",msg];
        NSString *tags5 = [NSString stringWithFormat:@"&action=%@",action];
        
        NSMutableString *addstr = [NSMutableString string];  //可变字符串
        [addstr appendString:tags5];
        [addstr appendString:tags1];
        [addstr appendString:tags2];
        [addstr appendString:tags3];
        [addstr appendString:tags4];
        
        
        if (debug) {
          NSString *debugemail = @"&to=zellop@21cn.com";
          [addstr appendString:debugemail];
        }
        
        bodystr = [bodystr stringByAppendingString:addstr]; //合并banner 和 post_content
        
        
        
    }else if ([type isEqualToString:@"register"]){  //联系我们 预约
#pragma remark 註冊用戶
        bodystr = [self registerBody:senddic];
    }else if ([type isEqualToString:@"resetpass"]){  //重置密码
#pragma remark 重置密码
        bodystr = [self resetpassBody:senddic];
    }else if ([type isEqualToString:@"getSchedule"]){
#pragma remark 本地推送
        bodystr = [self getscheduleBody:senddic];
    }
    
    
    NSLog(@"bodystr %@",bodystr);
    request.HTTPBody = [bodystr dataUsingEncoding:NSUTF8StringEncoding];
    
    //request.HTTPBody = [@"login_name=1&psw=111111&action=login" dataUsingEncoding:NSUTF8StringEncoding];
    
    
    //6.根据会话对象创建一个Task(发送请求）
    /*
     26      第一个参数：请求对象
     27      第二个参数：completionHandler回调（请求完成【成功|失败】的回调）
     28                 data：响应体信息（期望的数据）
     29                 response：响应头信息，主要是对服务器端的描述
     30                 error：错误信息，如果请求失败，则error有值
     31      */
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
        
        if (data && httpResponse.statusCode == 200) {
            //8.解析数据
            NSDictionary *datadic = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
            NSLog(@"%@",datadic.allValues);
            
            //                 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
           // NSLog(@"%@",datadic);
            
            //字符串先复制 再使用
            NSString *rc = [datadic valueForKey:@"rc"]; //[rc isEqualToString:@"1"]
            //NSString *rcstr = [NSString stringWithFormat:@"%@",@"1"];
            NSString *rcstr = [NSString stringWithFormat:@"%@",rc];
           // NSLog(@"rcstr %@",rcstr);
            
            NSString *scstr = [NSString stringWithFormat:@"%@",@"1"];
            //                 if ([rcstr isEqual:scstr]) {//如果相等true
            //                     NSLog(@"1 字符串相等");
            //                 }
            
            if ([type isEqualToString:@"Promotion"]) {
                scstr = [NSString stringWithFormat:@"%@",@"0"];
              
                NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
             
                if ([rcstr isEqual:scstr]) {
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"Promotionmail" object:[NSNumber numberWithInt:1] userInfo:dic];
                }else{
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"Promotionmail" object:[NSNumber numberWithInt:0] userInfo:dic];
                }
            }else if ([type isEqualToString:@"login"]){ //登录请求
               
                
                scstr = [NSString stringWithFormat:@"%@",@"0"];
                
                
                
                NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
                
                if ([rcstr isEqual:scstr]) {
                    NSLog(@"network 登錄成功");
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"loginstatus" object:[NSNumber numberWithInt:1] userInfo:dic];
                    
//                 NSMutableDictionary *dic2 = [dic mutableCopy];
//                 [DataPersist writeValueNSMutableDictionary:dic2  key:@"loginInfo"];//数据持久化
                 
                NSDictionary *datadic2 = [datadic valueForKey:@"data"];
                 //   NSLog(@"datadic2 %@",datadic2);
                NSString *wpuid = [datadic2 valueForKey:@"ID"];
                    NSLog(@"wpuid ID: %@",wpuid);
                [DataPersist writeValuePre:wpuid key:@"wpuid"];
                
                [[DataSource getInstance]setLoginFlag:TRUE]; //登錄狀態
                [DataPersist writeValuePre:@"1" key:@"loginStatus"];
                }else{
                    NSLog(@"network 登錄失敗");
                    NSString *statusstr1 = [NSString stringWithFormat:@"%@",@"-1"]; //缺少参数
                    NSString *statusstr2 = [NSString stringWithFormat:@"%@",@"-2"]; //用户不存在
                    NSString *statusstr3 = [NSString stringWithFormat:@"%@",@"-3"]; //密码错误
                    
                    if ([rcstr isEqual:statusstr1]){
                        [dic setValue:@"缺少参数" forKey:@"loginstatus"];
                    }else if ([rcstr isEqual:statusstr2]){
                        [dic setValue:@"用户不存在" forKey:@"loginstatus"];
                    }else if ([rcstr isEqual:statusstr3]){
                        [dic setValue:@"密码错误" forKey:@"loginstatus"];
                    }else{
                        NSLog(@"network 登錄失敗2  %@",rcstr);
                    }
                    
                    NSString *loginstatus = [dic valueForKey:@"loginstatus"];
                    NSLog(@"loginstatus %@",loginstatus);
                    
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"loginstatus" object:[NSNumber numberWithInt:0] userInfo:dic];
                }
            }else if ([type isEqualToString:@"contactUs"]) {
                    scstr = [NSString stringWithFormat:@"%@",@"0"];
                    
                    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
                
                    int backstatus = 0;
                    if ([rcstr isEqual:scstr]) {
//                        [[NSNotificationCenter defaultCenter]postNotificationName:@"contactUsBackAction" object:[NSNumber numberWithInt:1] userInfo:dic];
                        backstatus = 1;
                    }else{
                        backstatus = 0;
                    }
                
//                NSString *action = [sdic valueForKey:@"action"];
//                NSLog(@"action =%@",action);
//                if ([action isEqualToString:@"contact"]) {
//                     [[NSNotificationCenter defaultCenter]postNotificationName:@"contactUsBackAction" object:[NSNumber numberWithInt:backstatus] userInfo:dic];
//                } else {
 [[NSNotificationCenter defaultCenter]postNotificationName:@"contactUsBackAction" object:[NSNumber numberWithInt:backstatus] userInfo:dic];
               // }
                
            }else if ([type isEqualToString:@"register"]){ //註冊
                
                scstr = [NSString stringWithFormat:@"%@",@"0"];
                
                NSMutableDictionary *backdic = [[NSMutableDictionary alloc]init]; //返回數據字典
                
                if ([rcstr isEqual:scstr]) {
                    NSLog(@"network 註冊成功");
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"registerstatus" object:[NSNumber numberWithInt:1] userInfo:backdic];
                    
                }else{
                    NSLog(@"network 註冊失敗");
                    NSString *statusstr1 = [NSString stringWithFormat:@"%@",@"-1"]; //缺少参数
                    NSString *statusstr2 = [NSString stringWithFormat:@"%@",@"-2"]; //用户不存在
                    //NSString *statusstr3 = [NSString stringWithFormat:@"%@",@"-3"]; //密码错误
                  
                    
                    if ([rcstr isEqual:statusstr1]){
                        [backdic setValue:@"缺少参数" forKey:@"status"];
                    }else if ([rcstr isEqual:statusstr2]){
                        [backdic setValue:@"用户已存在" forKey:@"status"];
                    }
                    
//                    NSString *loginstatus = [backdic valueForKey:@"loginstatus"];
//                    NSLog(@"loginstatus %@",loginstatus);
                    
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"registerstatus" object:[NSNumber numberWithInt:0] userInfo:backdic];
                }
            }else if ([type isEqualToString:@"resetpass"]){ //重置密码
                
                scstr = [NSString stringWithFormat:@"%@",@"0"];
                
                NSMutableDictionary *backdic = [[NSMutableDictionary alloc]init]; //返回數據字典
                
                if ([rcstr isEqual:scstr]) {
                    NSLog(@"network 重置密码成功");
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"resetpassstatus" object:[NSNumber numberWithInt:1] userInfo:backdic];
                    
                }else{
                    NSLog(@"network 重置密码失敗");
                    NSString *statusstr1 = [NSString stringWithFormat:@"%@",@"-1"]; //缺少参数
                    NSString *statusstr2 = [NSString stringWithFormat:@"%@",@"-2"]; //用户不存在
                    NSString *statusstr3 = [NSString stringWithFormat:@"%@",@"-3"]; //发送失败
                    
                    
                    if ([rcstr isEqual:statusstr1]){
                        [backdic setValue:@"缺少参数" forKey:@"status"];
                    }else if ([rcstr isEqual:statusstr2]){
                        [backdic setValue:@"用户不存在" forKey:@"status"];
                    }else if ([rcstr isEqual:statusstr3]){
                        [backdic setValue:@"发送失败" forKey:@"status"];
                    }
                    
                    //                    NSString *loginstatus = [backdic valueForKey:@"loginstatus"];
                    //                    NSLog(@"loginstatus %@",loginstatus);
                    
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"resetpassstatus" object:[NSNumber numberWithInt:0] userInfo:backdic];
                }
            }else if ([type isEqualToString:@"getSchedule"]){
                #pragma remark 本地推送
                scstr = [NSString stringWithFormat:@"%@",@"0"];
                
                //NSMutableDictionary *backdic = [[NSMutableDictionary alloc]init]; //返回數據字典
                
                if ([rcstr isEqual:scstr]) {
                    NSLog(@"network 本地推送获取数据成功");
                    NSMutableArray *scharr = [datadic valueForKey:@"data"];
                    //NSLog(@"scharr %@",scharr);
                    
                    [DataPersist writeValueNSMutableArray:scharr key:savekey]; //数据持久化
                    
                    setLocalnoti *younglocalnoti = [[setLocalnoti alloc]init];
                    [younglocalnoti getScheduleAction];
                    
                   // [[NSNotificationCenter defaultCenter]postNotificationName:@"getScheduleStatus" object:[NSNumber numberWithInt:1] userInfo:backdic];
                    
                }else{
                    NSLog(@"network 本地推送获取数据失敗");
//                    NSString *statusstr1 = [NSString stringWithFormat:@"%@",@"-1"]; //缺少参数
//
//                    if ([rcstr isEqual:statusstr1]){
//                        [backdic setValue:@"缺少参数" forKey:@"netstatus"];
//                    }
//
//                  //  [[NSNotificationCenter defaultCenter]postNotificationName:@"getScheduleStatus" object:[NSNumber numberWithInt:0] userInfo:backdic];
                
                }
                //end
                
            }else{
            
                if ([rcstr isEqual:scstr]) {
                    NSLog(@"POST请求发送成功 ");
                    //                NSMutableDictionary *dic2 = [dic mutableCopy];
                    //                [DataPersist writeValueNSMutableDictionary:dic2  key:@"loginInfo"];//数据持久化
                    //
                    //                NSString *wpuid = [dic valueForKey:@"uid"];
                    //                [DataPersist writeValuePre:(NSString *)wpuid key:(NSString *)@"wpuid"];
                    
                }else{
                    NSLog(@"POST请求发送失败 ");
                }
                
            }
            
           
        }
        
        
        
    }];
    
    //7.执行任务
    [dataTask resume];
    
}

-(NSString*)registerBody:(NSMutableDictionary *)senddic{
    
    NSMutableDictionary *sdic = [senddic mutableCopy];
    NSString *bodystr = @"";
    //        NSLog(@"s接受到的 字典。%@",sdic);
    NSString *username = [sdic valueForKey:@"username"];
    NSString *userpass = [sdic valueForKey:@"userpass"];
    NSString *userphone = [sdic valueForKey:@"userphone"];
    NSString *useremail = [sdic valueForKey:@"useremail"];

    
    //bodystr = [NSString stringWithFormat:@"username=%@&userpass=%@&token=%@",username,phone,token];
    
    
    bodystr = [NSString stringWithFormat:@"username=%@",username];
    
    NSString *tags1 = [NSString stringWithFormat:@"&userpass=%@",userpass];
    NSString *tags2 = [NSString stringWithFormat:@"&userphone=%@",userphone];
    NSString *tags3 = [NSString stringWithFormat:@"&useremail=%@",useremail];
//    NSString *tags4 = [NSString stringWithFormat:@"&service=%@",service];
//    NSString *tags5 = [NSString stringWithFormat:@"&msg=%@",msg];
    
    
    NSMutableString *addstr = [NSMutableString string];  //可变字符串
    
    [addstr appendString:tags1];
    [addstr appendString:tags2];
    [addstr appendString:tags3];
//    [addstr appendString:tags4];
//    [addstr appendString:tags5];
    
    bodystr = [bodystr stringByAppendingString:addstr]; //合并banner 和 post_content
    return bodystr;
}

-(NSString*)resetpassBody:(NSMutableDictionary *)senddic{
    
    NSMutableDictionary *sdic = [senddic mutableCopy];
    NSString *bodystr = @"";
    //        NSLog(@"s接受到的 字典。%@",sdic);
//    NSString *username = [sdic valueForKey:@"username"];
//    NSString *userpass = [sdic valueForKey:@"userpass"];
//    NSString *userphone = [sdic valueForKey:@"userphone"];
    NSString *useremail = [sdic valueForKey:@"email"];
    
    
    //bodystr = [NSString stringWithFormat:@"username=%@&userpass=%@&token=%@",username,phone,token];
    
    
    bodystr = [NSString stringWithFormat:@"email=%@",useremail];
    
//    NSString *tags1 = [NSString stringWithFormat:@"&userpass=%@",userpass];
//    NSString *tags2 = [NSString stringWithFormat:@"&userphone=%@",userphone];
//    NSString *tags3 = [NSString stringWithFormat:@"&useremail=%@",useremail];
    //    NSString *tags4 = [NSString stringWithFormat:@"&service=%@",service];
    //    NSString *tags5 = [NSString stringWithFormat:@"&msg=%@",msg];
    
    
    NSMutableString *addstr = [NSMutableString string];  //可变字符串
    
//    [addstr appendString:tags1];
//    [addstr appendString:tags2];
//    [addstr appendString:tags3];
    //    [addstr appendString:tags4];
    //    [addstr appendString:tags5];
    
    bodystr = [bodystr stringByAppendingString:addstr]; //合并banner 和 post_content
    return bodystr;
}

-(NSString*)getscheduleBody:(NSMutableDictionary *)senddic{
    
    NSMutableDictionary *sdic = [senddic mutableCopy];
    NSString *bodystr = @"";

    //bodystr = [NSString stringWithFormat:@"username=%@&userpass=%@&token=%@",username,phone,token];
    
    NSString *tags1 = [NSString stringWithFormat:@"&%@=%@",[sdic valueForKey:@"client1"],[sdic valueForKey:@"client2"]];
    NSString *tags2 = [NSString stringWithFormat:@"&%@=%@",[sdic valueForKey:@"start1"],[sdic valueForKey:@"start2"]];
    NSString *tags3 = [NSString stringWithFormat:@"&%@=%@",[sdic valueForKey:@"end1"],[sdic valueForKey:@"end2"]];
    
    
    NSMutableString *addstr = [NSMutableString string];  //可变字符串
    [addstr appendString:tags1];
    [addstr appendString:tags2];
    [addstr appendString:tags3];

    bodystr = [bodystr stringByAppendingString:addstr]; //合并banner 和 post_content
    return bodystr;
}

@end
